﻿using Meow.Core.Simulation;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;

namespace Meow.Core.Graphics.Renderables
{
    public class MeshRenderable : Renderable
    {
        protected IMesh meshRef;

        public MatInstance Material { get; set; }

        public Matrix WorldTransformMatrix;

        public MeshRenderable(IMesh meshRef, MatInstance material, Matrix worldTransform)
        {
            this.meshRef = meshRef;
            Material = material;
            WorldTransformMatrix = worldTransform;
        }

        public override void Draw(in C_CameraRenderInfo camera, GraphicsDeviceManager gdm)
        {
            if (meshRef == null || meshRef?.VertexBuffer == null)
            {
                Debug.Log($"Renderable: meshRef == null || meshRef?.VertexBuffer == null");
                return;
            }

            if (meshRef.VertexBuffer.IsDisposed || meshRef.IndexBuffer.IsDisposed)
            {
                Debug.Log($"Renderable: meshRef.VertexBuffer.IsDisposed || meshRef.IndexBuffer.IsDisposed.");
                return;
            }

            //var size = _instances?.Length ?? 0;

            //if (size > 1)
            //{
            //    for (var i = 0; i < size; i++)
            //        _instances[i] = _transforms[i]._worldMatrix;

            //    if ((_instanceVertexBuffer == null) || (_instances.Length != _instanceVertexBuffer.VertexCount))
            //    {
            //        _instanceVertexBuffer?.Dispose();
            //        _instanceVertexBuffer = new DynamicVertexBuffer(graphics, instanceVertexDeclaration, _instances.Length, BufferUsage.WriteOnly);
            //    }

            //    _instanceVertexBuffer.SetData(_instances, 0, _instances.Length, SetDataOptions.Discard);

            //    graphics.SetVertexBuffers(new VertexBufferBinding(meshRef.VertexBuffer, 0, 0), new VertexBufferBinding(_instanceVertexBuffer, 0, 1));
            //    graphics.Indices = meshRef.IndexBuffer;
            //    graphics.DrawInstancedPrimitives(PrimitiveType.TriangleList, 0, 0, meshRef.Indices.Length / 3, _instances.Length);
            //}
            //else
            {
                Material.PrePassForward(in camera.PositionRender,in camera.ViewRender,in camera.ProjectionRender);
                Material.Pass(in WorldTransformMatrix, false, false);


                gdm.GraphicsDevice.SetVertexBuffer(meshRef.VertexBuffer);
                gdm.GraphicsDevice.Indices = meshRef.IndexBuffer;
                gdm.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, meshRef.IndexBuffer.IndexCount / 3);
            }
        }
    }
}
